package com.asit.listener;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.asit.secure.SecurityUtil;
import com.asit.service.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.SessionConnectEvent;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;

import java.security.Principal;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 监听websocket
 */
@Component
@Slf4j
public class StompConnectEventListener{
    @Autowired
    private RedisCache redisCache;
    @EventListener
    public void onConnectEvent(SessionConnectEvent event){
        log.info("{}","连接websocket");
        //获取Session连接信息
        StompHeaderAccessor sha = StompHeaderAccessor.wrap(event.getMessage());
        Principal user = event.getUser();
        log.info("{}",user.getName());
        String userId = BeanUtil.toBean(sha.getHeader("simpUser"), JSONObject.class).getStr("name");
        if(StrUtil.isNotBlank(userId)){
            log.info("{}",userId);
            //获取SessionId
            String sessionId = sha.getSessionId();

            SecurityUtil.getWebsocketSessionPool().put(userId,sessionId);

            //存储redis
            redisCache.setCacheObject("webSocket:"+userId,sessionId,1, TimeUnit.DAYS);
        }
    }
    @EventListener
    public void onDisconnectEvent(SessionDisconnectEvent event) {
        log.info("{}","关闭websocket");
        //获取Session连接信息
        StompHeaderAccessor sha = StompHeaderAccessor.wrap(event.getMessage());
        String userId = BeanUtil.toBean(sha.getHeader("simpUser"), JSONObject.class).getStr("name");
        log.info("{}",userId);
        if(StrUtil.isNotBlank(userId)){
            //获取SessionId
            String sessionId = sha.getSessionId();
            SecurityUtil.getWebsocketSessionPool().remove(userId);
            //redis删除此sessionId
            redisCache.deleteObject("webSocket:"+userId);
        }
    }
}
